package com.yicao.yicaomall.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.yicao.yicaomall.common.validator.group.AddGroup;
import com.yicao.yicaomall.common.validator.group.UpdateGroup;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.yicao.yicaomall.product.entity.CategoryEntity;
import com.yicao.yicaomall.product.service.CategoryService;
import com.yicao.yicaomall.common.utils.PageUtils;
import com.yicao.yicaomall.common.utils.R;

import javax.validation.Valid;


/**
 * 商品三级分类
 *
 * @author yicao
 * @email yicaozyq@gmail.com
 * @date 2023-10-31 16:57:55
 */
@RestController
@RequestMapping("product/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list/tree")
    public R tree() {
        List<CategoryEntity> list = categoryService.listWithTree();
        return R.ok().put("data", list);
    }

    /**
     * 列表
     */
//    @RequestMapping("/list")
//    @RequiresPermissions("product:category:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = categoryService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{catId}")
    public R info(@PathVariable("catId") Long catId) {
        CategoryEntity category = categoryService.getById(catId);

        return R.ok().put("category", category);
    }

    /**
     * 保存
     */
    @PostMapping("/info")
    public R save(@Validated({AddGroup.class}) @RequestBody CategoryEntity category) {
        categoryService.save(category);
        return R.ok();
    }

    @PutMapping("/list")
    public R saveBatch(@RequestBody CategoryEntity[] categories) {
        //todo:修改分类名时，也应该修改品牌分类关联表中的分类名
        categoryService.updateBatchById(Arrays.asList(categories));
        return R.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/info")
    public R update(@Validated({UpdateGroup.class}) @RequestBody CategoryEntity category) {
        boolean b = categoryService.updateById(category);
        System.out.println(b);
        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/list")
    public R delete(@RequestBody Long[] catIds) {
        categoryService.removeByIds(Arrays.asList(catIds));

        return R.ok();
    }

}
